package SA.student.question;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
import SA.student.MainActivity;
import SA.student.R;
import SA.student.notice.noticeActivity1;
import SA.student.shuttle.shuttleActivity1;
import SA.student.student.studentActivity1;
import android.app.*;
import android.content.*;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.widget.*;
import android.view.View.OnClickListener;

public class questionActivity1 extends Activity {

	ArrayList<QuestionData> arrData1;
	String id;
	String tempquestion;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.question1);


		Intent intent = getIntent();
		id = intent.getStringExtra("ID");


		String num = "";
		String title = "";
		String teacher = "";
		String yn = "N";

		int i = 0;

		questionnameparse qps = new questionnameparse();
		qps.run();// 공지
		arrData1 = new ArrayList<QuestionData>();

		String[] idlist = tempquestion.split("-");

		int tempnum = Integer.parseInt(idlist[0]);//제목수 스트링 형변환
		String[] noname = idlist[1].split(">");
		for (i = 0; i < tempnum; i++) {
			String[] tempcon = noname[i].split(",");
			num = tempcon[0];
			title = tempcon[1];
			teacher = tempcon[2];
			yn = tempcon[3];

			arrData1.add(new QuestionData(num, title, teacher, yn));
		}

		final QuestionAdapter MyAdapter = new QuestionAdapter(this,
				R.layout.question2_list, arrData1);

		ListView MyList;
		MyList = (ListView) findViewById(R.id.list);
		MyList.setAdapter(MyAdapter);

		ImageButton questionBtn = (ImageButton) findViewById(R.id.questionbtn);

		questionBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				new AlertDialog.Builder(questionActivity1.this)
				.setTitle("선생님을 선책해주세요.")
				.setItems(new String[] { "ㅁ", "ㅁ", "ㅁ" },
						new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog,
							int which) {
						// TODO Auto-generated method stub
						questionRegister();
					}
				}).show();
			}
		});

		MyList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			Intent questionView = new Intent(questionActivity1.this,
					questionActivity2_View.class);

			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				//String address = MyAdapter.getItem(position);
				questionView.putExtra("ID", id);
				startActivity(questionView);
			}

		});

		TextView noticeBtn = (TextView) findViewById(R.id.notice);
		noticeBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				noticeActivity();
			}
		});
		
		ImageView mainBtn = (ImageView) findViewById(R.id.mainBtn);
		mainBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mainActivity();
			}
		});
		
		ImageView studentBtn = (ImageView) findViewById(R.id.studentBtn);
		studentBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				studentActivity();
			}
		});

		ImageView shuttleBtn = (ImageView) findViewById(R.id.shuttleBtn);
		shuttleBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// TODO Auto-generated method stub
				shuttleActivity();
			}
		});
	}

	void mainActivity() {
		Intent intent = new Intent(this, MainActivity.class);
		intent.putExtra("ID", id);
		startActivity(intent);
	}

	void studentActivity() {
		Intent intent = new Intent(this, studentActivity1.class);
		intent.putExtra("ID", id);
		startActivity(intent);
	}

	void shuttleActivity() {
		Intent intent = new Intent(this, shuttleActivity1.class);
		intent.putExtra("ID", id);
		startActivity(intent);
	}

	void questionRegister() {
		Intent intent = new Intent(this, questionActivity3_Register.class);
		intent.putExtra("ID", id);
		startActivity(intent);
	}
	
	void noticeActivity(){
		Intent intent = new Intent(this, noticeActivity1.class);
		startActivity(intent);
	}

	public class questionnameparse implements Runnable {
		public void run() {

			// TODO Auto-generated method stub
			try {
				URL url = new URL("Http://220.67.128.8/questionname.php?id="+ URLEncoder.encode(id, "EUC-KR"));
				
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();

				InputStream is = null;
				ByteArrayOutputStream baos = null;
				if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					is = conn.getInputStream();
					baos = new ByteArrayOutputStream();
					byte[] byteBuffer = new byte[1024];
					byte[] byteData = null;
					int nLength = 0;
					while ((nLength = is.read(byteBuffer)) > 0) {
						baos.write(byteBuffer, 0, nLength);
					}
					byteData = baos.toByteArray();
					String response = new String(byteData, "euc-kr");
					if (response == null || response.equals("")) {
						throw new Exception("Response is NULL!");
					}
					tempquestion=response;
				} else {
					Log.e("login 응답 : ", "접속 안됨");
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
			}
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event){
		switch(keyCode){
		case KeyEvent.KEYCODE_BACK:
			String alertTitle = getResources().getString(R.string.app_name);
			String buttonMessage = getResources().getString(R.string.alert_msg_exit);
			String buttonYes = getResources().getString(R.string.button_yes);
			String buttonNo = getResources().getString(R.string.button_no);

			new AlertDialog.Builder(questionActivity1.this)
			.setTitle(alertTitle)
			.setMessage(buttonMessage)
			.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					moveTaskToBack(true);
					finish();
				}
			})
			.setNegativeButton(buttonNo, null)
			.show();
		}
		return true;
	}
}

class QuestionData {
	String qNumber;
	String qTitle;
	String qTeacher;
	String qAnswer;

	public QuestionData(String num, String title, String teacher, String yn) {
		// TODO Auto-generated constructor stub
		qNumber = num;
		qTitle = title;
		qTeacher = teacher;
		qAnswer = yn;
	}
}

class QuestionAdapter extends BaseAdapter {
	Context maincon;
	LayoutInflater Inflater;
	ArrayList<QuestionData> arSrc;
	int layout;

	public QuestionAdapter(Context context, int alayout, ArrayList<QuestionData> aarSrc) {
		maincon = context;
		Inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		arSrc = aarSrc;
		layout = alayout;
	}

	public int getCount() {
		return arSrc.size();
	}

	public String getItem(int position) {
		return arSrc.get(position).qTitle;
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
	//	final int pos = position;
		if (convertView == null) {
			convertView = Inflater.inflate(layout, parent, false);
		}

		TextView qNumberTxt = (TextView) convertView.findViewById(R.id.qNumber);
		qNumberTxt.setText(arSrc.get(position).qNumber);

		TextView qTitleTxt = (TextView) convertView.findViewById(R.id.qTitle);
		qTitleTxt.setText(arSrc.get(position).qTitle);

		TextView qTeacherTxt = (TextView) convertView
				.findViewById(R.id.qTeacher);
		qTeacherTxt.setText(arSrc.get(position).qTeacher);

		TextView qAnswerTxt = (TextView) convertView.findViewById(R.id.qAnswer);
		qAnswerTxt.setText(arSrc.get(position).qAnswer);

		return convertView;
	}
}
